package com.etocrm.saas.lib.base.resource.user;

import cn.hutool.core.util.StrUtil;
import cn.hutool.crypto.digest.DigestUtil;
import com.alibaba.fastjson.JSONObject;
import com.etocrm.saas.lib.base.cache.redis.redisson.service.StringRedisClient;
import com.etocrm.saas.lib.base.common.result.Result;
import com.etocrm.saas.lib.base.common.vo.UserInfoVO;
import com.etocrm.saas.lib.base.resource.cache.UserLoginCacheKey;
import com.fasterxml.jackson.databind.ObjectMapper;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.context.request.RequestAttributes;
import org.springframework.web.context.request.RequestContextHolder;
import org.springframework.web.context.request.ServletRequestAttributes;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

/**
 * 获取第三方API用户信息
 */
@Slf4j
public class ApiUserInfoUtil {

    public static final String TOKEN_HEADER_KEY = "Authorization";

    @Autowired
    private StringRedisClient stringRedisClient;

    public UserInfoVO getLoginUser() {
        String token = getToken();
        if (StringUtils.isEmpty(token)) {
            return null;
        }
        String tokenMD5 = DigestUtil.md5Hex(token);
        String json = stringRedisClient.get(new UserLoginCacheKey(tokenMD5));
        if (StringUtils.isEmpty(json)) {
            log.warn("token : {}  ; MD5 : {} , 无该用户登录信息...", token, tokenMD5);
            return null;
        }
        UserInfoVO authUser = JSONObject.parseObject(json, UserInfoVO.class);
        return authUser;
    }

    public String getToken() {
        RequestAttributes requestAttributes = RequestContextHolder.getRequestAttributes();
        if (requestAttributes != null) {
            ServletRequestAttributes servletRequestAttributes = (ServletRequestAttributes) requestAttributes;
            String authorization = servletRequestAttributes.getRequest().getHeader(TOKEN_HEADER_KEY);
            if(StringUtils.isEmpty(authorization)){
                return null;
            }
            String jwt = authorization.substring(7);
            return jwt;
        }
        return StrUtil.EMPTY;
    }

}
